package com.esender.ordermanage.service.impl;

import com.esender.ordermanage.config.RabbitMQConfig;
import com.esender.ordermanage.mapper.OrderManageMapper;
import com.esender.ordermanage.service.OrderManageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.UUID;

@Service
@Slf4j
public class OrderManageServiceImpl implements OrderManageService {
    @Resource
    private OrderManageMapper orderManageMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public void save() {
        String id = UUID.randomUUID().toString();
        orderManageMapper.save(id);
        //发送消息到普通交换机等待15s时间
        rabbitTemplate.convertAndSend(RabbitMQConfig.ORDER_EXCHANGE, "", id, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                // 设置消息的生存时间是15s，当然也可以在构建对列的时候，指定队列的生存时间
                message.getMessageProperties().setExpiration("15000");
                return message;
            }
        });
    }

    @Override
    @Transactional
    public void delayCancelOrder(String msg) {
        // 先根据msg查询订单信息
        int orderStateById = orderManageMapper.findOrderStateById(msg);
        if (orderStateById == 1){
            log.info("订单已经支付"+msg);
            return;
        }
        // 修改订单状态
        log.info("订单未支付，修改订单状态为已取消");
        orderManageMapper.updateOrderStateById(msg,-1);
    }
}
